package com.uenpay.im.ui.old.activity.stickers;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qyx.android.weight.choosemorepic.PhotoItem;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.choosemorepic.PhotoActivity;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.weight.DialogUtility;
import com.uenpay.im.weight.ZProgressHUD;
import com.uenpay.util.app.base.BaseActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.MessageFormat;
import java.util.ArrayList;

/**
 * @author SL
 * @version 1.0
 * @copyRight http://www.qiyunxin.com
 * @date 2016-6-1 下午1:14:04
 * @function 我添加的表情列表
 */
public class StickerActivity extends BaseActivity {

    private StickerAdapter mStickerAdapter;
    private GridView sticker_gd;
    private boolean is_arran = false;
    private LinearLayout bottom_layout;
    private View bottom_view;
    private Button delete_btn;
    private TextView total_tv;
    private ZProgressHUD zProgressHUD = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_sticker_layout;
    }

    @Override
    public void initView(View view) {
        initView();
        initListener();
        // initData();
        getCustomList();
    }

    protected void initView() {
        zProgressHUD = new ZProgressHUD(this);
        ((TextView) findViewById(R.id.title_textview))
                .setText(R.string.my_added_face);
        sticker_gd = (GridView) findViewById(R.id.sticker_gd);
        ((TextView) findViewById(R.id.title_right_tv))
                .setText(R.string.arrangement);
        findViewById(R.id.title_right_layout).setVisibility(View.VISIBLE);
        bottom_layout = (LinearLayout) findViewById(R.id.bottom_layout);
        bottom_view = findViewById(R.id.bottom_view);
        total_tv = (TextView) findViewById(R.id.total_tv);
        delete_btn = (Button) findViewById(R.id.delete_btn);
    }

    protected void initListener() {
        sticker_gd.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                StickerEntity mCustomEntity = (StickerEntity) arg0.getAdapter()
                        .getItem(arg2);
                if (mCustomEntity != null) {
                    if (is_arran) {
                        mStickerAdapter.setSelected(arg2);
                        getDeleteCount();
                    } else {
                        if (TextUtils.isEmpty(mCustomEntity.customeFaceUrl)) {
                            // 跳转到相册
                            Intent getImage = new Intent(StickerActivity.this,
                                    PhotoActivity.class);
                            getImage.putExtra("max_select_count", 1);
                            startActivityForResult(getImage, 100);
                        }
                    }
                }
            }
        });

        findViewById(R.id.title_right_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        is_arran = !is_arran;
                        updateArranView();
                    }
                });
        delete_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String strs = mStickerAdapter.getSelecedSticker();
                if (!TextUtils.isEmpty(strs)) {
                    showDeleteDialog(strs);
                }
            }
        });
    }

    /**
     * 删除表情对话框
     *
     * @param deleteIds
     */
    private void showDeleteDialog(final String deleteIds) {
        DialogUtility.showDialog(StickerActivity.this,
                R.string.delete_seleced_custom_face, R.string.sure,
                R.string.cancel, true, new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        deleteCustomFace(deleteIds);
                    }
                });
    }

    /**
     * 删除所选表情
     *
     * @param favoriteids
     */
    private void deleteCustomFace(String favoriteids) {
        zProgressHUD.show();
        StickersHandle.deleteCustomFace(favoriteids,
                new StickersHandle.IDeleteCustomListener() {

                    @Override
                    public void onDeleteResult(int status, String msg) {

                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            // 通知会话页面更新数据
                            Intent intent = new Intent(BroadcastAction.ACTION_REFRESH_STICKER);
                            IMApplication.getAppContext().sendBroadcast(intent);
                            getCustomFaces();
                        } else if (!TextUtils.isEmpty(msg)) {
                            IMApplication.showToast(msg);
                            zProgressHUD.dismiss();
                        }
                    }
                });
    }

    private void getCustomFaces() {
        StickersHandle.getCustomFaceList(new StickersHandle.IGetCustomFaceListener() {

            @Override
            public void onGetCustomFaceResult(int status, String msg,
                                              ArrayList<StickerEntity> arrayList) {
                zProgressHUD.dismiss();
                if (status == HttpInvokeResultCode.RESULT_OK) {
                    is_arran = false;
                    updateArranView();
                }
            }
        });
    }

    /**
     * 修改显示管理状态
     */
    private void updateArranView() {
        initData();
        mStickerAdapter.setManage(is_arran);
        if (is_arran) {
            bottom_view.setVisibility(View.VISIBLE);
            bottom_layout.setVisibility(View.VISIBLE);
            total_tv.setText(MessageFormat.format(
                    getResources().getString(R.string.total_custom),
                    mStickerAdapter.getCount()));
            ((TextView) findViewById(R.id.title_right_tv))
                    .setText(R.string.cancel);
        } else {
            bottom_view.setVisibility(View.GONE);
            bottom_layout.setVisibility(View.GONE);
            delete_btn.setText(R.string.delete);
            ((TextView) findViewById(R.id.title_right_tv))
                    .setText(R.string.arrangement);
        }
    }

    /**
     * 获取要删除的个数
     */
    private void getDeleteCount() {
        int count = mStickerAdapter.getDeleteCount();
        if (count == 0) {
            delete_btn.setText(R.string.delete);
        } else {
            delete_btn.setText(getResources().getString(R.string.delete) + "("
                    + count + ")");
        }
    }

    /**
     * 获取服务器列表数据
     */
    private void getCustomList() {
        StickersHandle.getCustomFaceList(new StickersHandle.IGetCustomFaceListener() {

            @Override
            public void onGetCustomFaceResult(int status, String msg,
                                              ArrayList<StickerEntity> arrayList) {
                if (status == HttpInvokeResultCode.RESULT_OK) {
                    initData();
                }
            }
        });
    }

    /**
     * 读取本地表情数据
     */
    private void initData() {
        ArrayList<StickerEntity> arrayList = new ArrayList<StickerEntity>();

        String customJsonStr = IMApplication.config
                .getCustomFaceJson(IMApplication.getCustId());
        JSONArray jsonArray = null;
        if (!TextUtils.isEmpty(customJsonStr)) {
            try {
                jsonArray = new JSONArray(customJsonStr);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            jsonArray = new JSONArray();
        }

        if (jsonArray != null && jsonArray.length() > 0) {
            for (int i = 0, size = jsonArray.length(); i < size; i++) {
                JSONObject jsonObject = jsonArray.optJSONObject(i);
                if (jsonObject != null) {
                    StickerEntity customEntity = new StickerEntity();
                    customEntity.fileId = jsonObject.optString("fileid");
                    customEntity.fileHash = jsonObject.optString("filehash");
                    customEntity.favoriteid = jsonObject
                            .optString("favoriteid");
                    customEntity.customeFaceUrl = jsonObject
                            .optString("customefaceurl");
                    arrayList.add(customEntity);
                }

            }
        }

        if (!is_arran) {
            StickerEntity customEntity = new StickerEntity();
            customEntity.customeFaceUrl = "";
            arrayList.add(customEntity);
        }
        if (mStickerAdapter == null)
            mStickerAdapter = new StickerAdapter(StickerActivity.this,
                    arrayList);
        else
            mStickerAdapter.setData(arrayList);
        sticker_gd.setAdapter(mStickerAdapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == RESULT_OK) {

            /** 相册 **/
            ArrayList<PhotoItem> select_gl_arr = (ArrayList<PhotoItem>) data
                    .getSerializableExtra("gl_arr");
            if (select_gl_arr.size() > 0) {
                for (int i = 0; i < select_gl_arr.size(); i++) {
                    String path = select_gl_arr.get(i).getPath();
                    Intent intent = new Intent(StickerActivity.this,
                            CreateStickerActivity.class);
                    intent.putExtra("path", path);
                    startActivityForResult(intent, 101);
                }
            }
        } else if (requestCode == 101 && resultCode == RESULT_OK) {
            initData();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}
